package com.lw.leetcode.arr.b;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * arr
 * 1297. 子串的最大出现次数
 *
 * @author liw
 * @version 1.0
 * @date 2021/12/20 20:39
 */
public class MaxFreq {

    public static void main(String[] args) {
        MaxFreq test = new MaxFreq();

        // 3
//        String str = "aaaa";
//        int a = 2;
//        int b = 2;
//        int c = 4;

        // 3
        String str = "aabcabcab";
        int a = 2;
        int b = 2;
        int c = 3;
        int i = test.maxFreq(str, a, b, c);
        System.out.println(i);
    }

    public int maxFreq(String s, int maxLetters, int minSize, int maxSize) {
        int[] arr = new int[26];
        Map<String, Integer> map = new HashMap<>();
        for (int i = 0; i < minSize; i++) {
            arr[s.charAt(i) - 'a']++;
        }
        int count = 0;
        for (int i = 0; i < 26; i++) {
            if (arr[i] != 0) {
                count++;
            }
        }
        if (count <= maxLetters) {
            map.merge(s.substring(0, minSize), 1, (a, b) -> a + b);
        }
        int length = s.length();
        for (int i = minSize; i < length; i++) {
            int a = s.charAt(i) - 'a';
            int b = s.charAt(i - minSize) - 'a';
            if (arr[a] == 0) {
                count++;
            }
            arr[a]++;
            if (arr[b] == 1) {
                count--;
            }
            arr[b]--;

            if (count <= maxLetters) {
                map.merge(s.substring(i - minSize + 1, i + 1), 1, (a1, a2) -> a1 + a2);
            }
        }
        int max = 0;
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            max = Math.max(max, entry.getValue());
        }
        return max;
    }

}
